package smarthouse.ejb;

import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import smarthouse.conv.Conversions;
import smarthouse.dto.ElectronicDTO;
import smarthouse.model.Electronic;

/**
 * Session Bean implementation class ElectronicDAO
 */
@Stateless
@Local
public class ElectronicDAO implements ElectronicDAORemote {

	@EJB
	Conversions conv;

	@PersistenceContext
	EntityManager em;

	/**
	 * Default constructor.
	 */
	public ElectronicDAO() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public ElectronicDTO getElectronicbyId(int id) {
		TypedQuery<Electronic> usersReturn = em.createNamedQuery(
				"Electronic.findAll", Electronic.class);

		List<Electronic> users = usersReturn.getResultList();
		for (Electronic u : users) {
			if (u.getElectronicId() == id) {
				return conv.electronic_C_2_DTO(u);
			}
		}

		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean addElectronic(ElectronicDTO user) {
		Electronic u = em.find(Electronic.class, user.getElectronicId());

		if (u == null) {
			em.persist(conv.electronic_DTO_2_C(user));
			return true;
		} else {
			em.merge(conv.electronic_DTO_2_C(user));
			return true;
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean updateElectronic(ElectronicDTO user) {
		Electronic u = em.find(Electronic.class, user.getElectronicId());

		if (u == null) {
			return false;
		} else {
			u.setElectronicId(user.getElectronicId());
			u.setPower(user.getPower());
			u.setType(user.getType());
			em.merge(u);
			return true;
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean removeElectronic(int id) {
		Electronic u = em.find(Electronic.class, id);

		if (u == null) {
			return false;
		} else {
			em.remove(id);
			return true;
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void houseShutdown() {
		TypedQuery<Electronic> usersReturn = em.createNamedQuery(
				"Electronic.findAll", Electronic.class);

		List<Electronic> users = usersReturn.getResultList();
		for (Electronic e : users) {
			e.setPower(0);
			em.merge(e);
		}

	}
}
